<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="visible"
               v-loading="loading"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="80%">
      <el-form :model="formdata"
               label-position="right"
               ref="formdataRef"
               label-width="150px"
               :rules='formdataRules'>
        <el-form-item label="投放机构："
                      prop="type">
          <el-radio-group v-model="formdata.type"
                          @change="checkBox"
                          :disabled="dataObj ? true: false">
            <el-radio :label="0">所有B端机构</el-radio>
            <el-radio :label="1">按区域投放</el-radio>
            <el-radio :label="2">指定机构</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="请选择区域："
                      v-if="formdata.type === 1">
          <el-checkbox-group v-model="formdata.type">
            <el-card class="box-card">
              <div slot="header"><span class="tip">最少勾选一个区域</span></div>
              <div>
                <el-checkbox-group v-model="formdata.ids">
                  <el-checkbox v-for="item in provinceList"
                               :label="item.id"
                               :key="item.id">{{item.name}}</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-card>
          </el-checkbox-group>
        </el-form-item>
        <template v-if="formdata.type === 2">
          <el-form-item label="搜索机构：">
            <el-select v-model="formdata.ids"
                       ref="selectDom"
                       placeholder="请选择搜索机构"
                       multiple
                       filterable
                       remote
                       reserve-keyword
                       :remote-method="remoteMethod"
                       :loading="loading1"
                       class="w-200"
                       @change="handleSelect">
              <el-option v-for="item in options4"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
            <el-button type="primary"
                       @click="handleAdd(formdata.ids)">增 加</el-button>
          </el-form-item>
          <el-form-item label="已选机构：">
            <el-table :data="dataList"
                      style="width: 50%"
                      border>
              <el-table-column prop="name"
                               label="机构名称">
              </el-table-column>
              <el-table-column prop="address"
                               label="机构地址">
              </el-table-column>
              <el-table-column prop="op"
                               label="操作"
                               width="120">
                <template slot-scope="scope">
                  <el-button type="danger"
                             @click="delRow(dataList, scope.$index)">移 除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="success"
                     @click="handleOption('add', null ,null)">新 增</el-button>
          <el-table :data="formdata.advertisingList"
                    style="width: 100%"
                    border
                    class="mt-20">
            <el-table-column prop="title"
                             label="广告标题">
              <template slot-scope="scope">
                <el-form-item :rules="listRules.title"
                              :prop="'advertisingList.' + scope.$index + '.title'">
                  <el-input v-model="scope.row.title"
                            class="w-200"
                            placeholder="请输入广告标题"
                            maxlength="20"
                            show-word-limit></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="sort"
                             label="广告排序">
              <template slot-scope="scope">
                <el-form-item :rules="listRules.sort"
                              :prop="'advertisingList.' + scope.$index + '.sort'">
                  <el-input v-model.number="scope.row.sort"
                            class="w-200"
                            placeholder="请输入广告排序"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="advertising"
                             label="广告语">
              <template slot-scope="scope">
                <el-form-item :rules="listRules.advertising"
                              :prop="'advertisingList.' + scope.$index + '.advertising'">
                  <el-input v-model="scope.row.advertising"
                            class="w-200"
                            placeholder="请输入广告语"
                            maxlength="20"
                            show-word-limit></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="logoUrl"
                             label="广告图片">
              <template slot-scope="scope">
                <el-form-item :rules="listRules.logoUrl"
                              :prop="'advertisingList.' + scope.$index + '.logoUrl'">
                  <el-upload class="avatar-uploader"
                             :action="imageUploadUrl"
                             :show-file-list="false"
                             :on-success="(response, file, fileList) => handlePictureCardPreview(response, file, fileList, scope.$index)"
                             :before-upload="beforeAvatarUpload">
                    <img v-if="scope.row.logoUrl"
                         :src="scope.row.logoUrl"
                         style="width:100px;height:100px;" />
                    <i v-else
                       class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="option"
                             label="操作"
                             align="center"
                             width="120">
              <template slot-scope="scope">
                <el-button type="danger"
                           @click="handleOption('del', scope.$index, formdata.advertisingList)">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="投放截止日期："
                      prop="expirationTime">
          <el-date-picker v-model="formdata.expirationTime"
                          :picker-options="pickerOptions"
                          type="datetime"
                          value-format="timestamp"
                          placeholder="请选择投放截止日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <p align="center">
        <el-button @click="modalClose"
                   type="info">取 消</el-button>
        <el-button type="primary"
                   @click="onSubmit(saveType)">保 存</el-button>
      </p>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'ticketDialog', // 小票广告管理弹窗
    props: {
      dataObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      }
    },
    data () {
      var checkInputNum = (rule, value, callback) => {
        let data = this.formdata.advertisingList;
        if (!value) {
          return callback(new Error('请输入广告排序'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入整数'));
          } else {
            callback();
            /* if (data && data.length > 0) {
              for (let i = 0; i < data.length - 1; i++) {
                for (let j = i + 1; j < data.length; j++) {
                  if (data[j]['sort'] === data[i]['sort']) {
                    callback(new Error('排序重复'))
                  }
                }
              }
            } else {
              callback();
            } */
          }
        }, 0);

      };
      return {
        title: '新 增',
        loading: false,
        loading1: false,
        imageUploadUrl: this.api.appUpgradeUpload.url,
        formdata: {
          type: 0,
          expirationTime: '',
          ids: [],
          isUp: 1,
          advertisingList: [
            { id: null, title: '', sort: '', advertising: '', logoUrl: '' }
          ]
        },
        formdataRules: {
          expirationTime: [
            { required: true, message: '请选择投放截止日期', trigger: ['chagne', 'blur'] }
          ],
          /*  ids: [
             { required: true, message: '请选择至少一个区域', trigger: ['chagne', 'blur'] }
           ] */
        },
        listRules: {
          title: [
            { required: true, message: '请输入广告标题', trigger: 'blur' }
          ],
          sort: [
            { validator: checkInputNum, trigger: ['change', 'blur'] }
          ],
          advertising: [
            { required: true, message: '请输入广告语', trigger: 'blur' }
          ],
          logoUrl: [
            { required: true, message: '请选择广告图片', trigger: ['chagne', 'blur'] }
          ],
        },
        saveType: 'addSave',
        provinceList: [],
        options4: [],
        dataList: [],
        lists: [],
        pickerOptions: { // 禁用当前日期之前的日期
          disabledDate (time) {
            // Date.now()是javascript中的内置函数，它返回自1970年1月1日00:00:00 UTC以来经过的毫秒数。
            return time.getTime() < Date.now() - 8.64e7;
          },
        },
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      // 动态添加行
      handleOption (op, index, data) {
        switch (op) {
          case 'add':
            if (this.formdata.advertisingList.length < 5) {
              this.formdata.advertisingList.push({
                id: null,
                title: '',
                sort: '',
                advertising: '',
                logoUrl: ''
              })
            } else {
              this.$message.warning('最多添加5个广告!');
            }
            break;
          case 'del':
            /* if (data.length == 1) {
              this.$message.warning('至少保留1个广告!');
              return
            } else {
              data.splice(index, 1);
            } */
            data.splice(index, 1);
            break;
        }
      },

      // 上传前的方法
      beforeAvatarUpload (file) {
        let types = ['image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'image/bmp']
        const isType = types.includes(file.type);
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isType) {
          this.$message.error('上传图片必须是JPG/JPEG/GIF/PNG/BMP 格式!');
          return isType;
        }
        if (!isLt10M) {
          this.$message.error('上传图片大小不能超过 10MB!');
          return isLt10M;
        }
      },
      // 上传单张图片
      handlePictureCardPreview (response, file, fileList, index) {
        if (response.code === '200') {
          // 状态码为200时则上传成功
          this.formdata.advertisingList[index]['logoUrl'] = file.response.object[0];
          this.$message.success('上传成功');
        } else {
          // 状态码不是200时上传失败 从列表中删除
          fileList.splice(fileList.indexOf(file), 1);
          this.$message.error(response.message);
        }
      },
      checkBox (val) {
        if (val === 1) {
          this.getChildrenArea();
        }
        this.formdata.advertisingList = [];
        this.formdata.ids = [];
        this.dataList = [];
        // this.$refs.formdataRef.resetFields();
      },


      // 选择省
      async getChildrenArea () {
        const { data: res } = await this.post(this.api.codeConfig.getChildrenArea, {
          id: 0
        })
        if (res.code === '200') {
          this.provinceList = res.object;
        }
      },
      // 保存
      onSubmit (saveType) {
        this.$refs.formdataRef.validate(async (valid) => {
          if (valid) {
            // 新增保存
            if (saveType === 'addSave') {
              if (this.formdata.type === 1) {
                if (this.formdata.ids.length === 0) {
                  this.$message.error('最少勾选一个区域！');
                  return
                }
              }
              if (this.formdata.type === 2) {
                if (this.dataList.length === 0) {
                  this.$message.error('请选择搜索机构！');
                  return
                }
              }
              if (this.formdata.advertisingList.length === 0) {
                this.$message.error('至少添加1个广告!');
                return
              }
              const { data: res } = await this.post(this.api.promote.saveAdvertising, this.formdata);
              if (res.code === '200') {
                this.$message.success('保存成功!');
                this.$parent.getList(); // 调用父件组方法
                this.modalClose();
              }
            }
            // 编辑保存
            if (saveType === 'editSave') {
              if (this.formdata.type === 2) {
                if (this.dataList.length === 0) {
                  this.$message.error('请选择搜索机构！');
                  return
                }
                this.formdata.ids = this.dataList.map(item => item.id);
              }
              if (this.formdata.type === 1) {
                if (this.formdata.ids.length === 0) {
                  this.$message.error('最少勾选一个区域！');
                  return
                }
              }
              if (this.formdata.advertisingList.length === 0) {
                this.$message.error('至少添加1个广告!');
                return
              }
              const { data: res } = await this.post(this.api.promote.updateAdvertising, {
                ...this.formdata,
                isUp: this.dataObj.isUp
              });
              if (res.code === '200') {
                this.$message.success('保存成功!');
                this.$parent.getList(); // 调用父件组方法
                this.modalClose();

              }
            }
          }
        })
      },

      // 查询详情
      async getDetail () {
        const { type, pushTime, expirationTime } = this.dataObj;
        const { data: res } = await this.post(this.api.promote.detailAdvertising, {
          type: type,
          pushTime: pushTime,
          expirationTime: expirationTime
        })
        if (res.code === '200') {
          this.formdata = res.object;
          // 按区域投放
          if (this.formdata.type === 1) {
            this.getChildrenArea();
            let ids = res.object.mechanismInfoList.map(item => item.id);
            this.$set(this.formdata, 'ids', ids);
          }
          // 指定机构
          if (this.formdata.type === 2) {
            this.dataList = res.object.mechanismInfoList;
            let ids = res.object.mechanismInfoList.map(item => item.id);
            // this.$set(this.formdata, 'ids', ids);
          }
        }
      },
      // 远程搜索医生
      remoteMethod (query) {
        if (query !== '') {
          this.loading1 = true;
          let _this = this;
          this.post(this.api.regist.searchHospitalByES, {
            name: query
          }).then(res => {
            if (res.data.code === '200') {
              this.loading1 = false;
              _this.lists = res.data.object;
            }
          })
          setTimeout(() => {
            this.loading1 = false;
            this.options4 = this.lists.filter(item => item.name.indexOf(query) > -1);
          }, 200)
        } else {
          this.options4 = [];
        }
      },

      handleSelect (item) {
        this.formdata.ids = item;
      },
      // 增加机构
      handleAdd (params) {
        let temp = this.lists.filter(item => params.some(ele => ele === item.id)).map(v => ({ id: v.id, name: v.name, address: v.address }));
        this.dataList = this.removeDuplicatedItem([...this.dataList, ...temp], 'id');
      },
      removeDuplicatedItem (arr, key) {
        var result = [];
        var obj = {};
        for (var i = 0; i < arr.length; i++) {
          if (!obj[arr[i][key]]) {
            result.push(arr[i]);
            obj[arr[i][key]] = true;
          }
        }
        return result;
      },
      // 删除已选机构
      delRow (table, index) {
        table.splice(index, 1);
      }
    },
    created () {
      if (this.dataObj) {
        this.getDetail(); // 查询详情
        this.title = '编 辑';
        this.saveType = 'editSave';

      } else {
        this.saveType = 'addSave';
      }
    },


  }
</script>
<style scoped lang="scss">
  .box-card {
    width: 50%;
    /deep/ .el-card__header {
      padding: 5px 20px 0;
    }
    .tip {
      font-size: 14px;
    }
  }

  .avatar-uploader /deep/.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100x;
    height: 100px;
    display: block;
  }
</style>